package com.at.bilibili.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.at.bilibili.dao.UserMomentsDao;
import com.at.bilibili.domain.UserMoment;
import com.at.bilibili.domain.constant.MQConstant;
import com.at.bilibili.service.util.RocketMQUtil;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
public class UserMomentsService {
    @Autowired
    private UserMomentsDao userMomentsDao;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public List<UserMoment> getUserSubscribedMoments(Long userId) {
        // redis中的key
        String key = "subscribed-" + userId;
        String listStr = redisTemplate.opsForValue().get(key);
        System.out.println("-------------------");
        System.out.println(listStr);
        System.out.println("-------------------");
        return JSONArray.parseArray(listStr, UserMoment.class);

    }

    public void addUserMoments(UserMoment userMoment) throws RemotingException, InterruptedException, MQClientException, MQBrokerException {
        userMoment.setCreateTime(new Date());
        userMoment.setUpdateTime(new Date());
        userMomentsDao.addUserMoments(userMoment);
        // 已经产生动态 -> 发送消息到MQ
        // 利用ApplicationContext获取producer
        DefaultMQProducer producer = (DefaultMQProducer) applicationContext.getBean("momentsProducer");
        // 消息保存的是内容的byte数组
        Message msg = new Message(MQConstant.TOPIC_MOMENTS, JSONObject.toJSONString(userMoment).getBytes(StandardCharsets.UTF_8));
        RocketMQUtil.syncSendMsg(producer, msg);
    }
}
